package com.mikao.service.impl;


import cn.jiguang.common.utils.StringUtils;
import com.mikao.constant.ErrorCode;
import com.mikao.dto.bo.VerifyCodeForm;
import com.mikao.dto.vo.BaseResult;
import com.mikao.service.VerifyCodeService;
import com.mikao.util.RandomUtil;
import com.mikao.util.SmsUtil;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.concurrent.TimeUnit;

/**
 * @author KennyDavid
 */

@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {

    private RedisTemplate<String, String> redisTemplate;

    public VerifyCodeServiceImpl(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    @Transactional
    public BaseResult sendVerifyCode(String mobile) {
        String code = RandomUtil.generate(6);
        redisTemplate.opsForValue().set(mobile, code, 15, TimeUnit.MINUTES);
        try {
            SmsUtil.sendSms(mobile, code);
        } catch (Exception e) {
            throw new RedisSystemException("exception", e);
        }
        return new BaseResult(ErrorCode.SUCCESS.getCode(), "验证码发送成功");
    }

    @Override
    public BaseResult checkVerifyCode(VerifyCodeForm verifyCodeForm) {
        String code = redisTemplate.opsForValue().get(verifyCodeForm.getAccount());
        if (StringUtils.isEmpty(code)) {
            return new BaseResult(ErrorCode.PHONE_CODE_ERROR.getCode(), ErrorCode.PHONE_CODE_ERROR.getMsg());
        }
        if (code.equals(verifyCodeForm.getPhoneCode())) {
            return new BaseResult(ErrorCode.SUCCESS.getCode(), "验证码正确");
        }
        return new BaseResult(ErrorCode.PHONE_CODE_ERROR.getCode(), ErrorCode.PHONE_CODE_ERROR.getMsg());
    }
}
